<script setup lang="ts">
import type { IConversation } from "@src/types";
import type { Ref } from "vue";
import { computed, inject, onMounted, onUpdated, ref } from "vue";

import useStore from "@src/store/store";
import InfiniteLoading from "v3-infinite-loading";

import Message from "@src/components/views/HomeView/Chat/ChatMiddle/Message/Message.vue";
import TimelineDivider from "@src/components/views/HomeView/Chat/ChatMiddle/TimelineDivider.vue";
import useCustomerStore from "@src/store/customerStore";
import { isToday, isYestoday } from "@src/utils";
import { getHistory } from "@src/network/api";

const store = useStore();
const customerStore = useCustomerStore()
const container: Ref<HTMLElement | null> = ref(null);
const conversations = computed(()=> {
  if(customerStore.conversations){
    const keys = Object.keys(customerStore.conversations);
    keys.sort(function(a,b){return parseInt(a) - parseInt(b);});
    const sorted:IConversation[] = [];
    keys.forEach(key => {
      sorted.push(customerStore.conversations[key]);
    });
    return sorted;
  }else{
    return [];
  }
})

var preScrollHeight = 0;

// checks whether the previous message was sent by the same user.
const isFollowUp = (index: number, previousIndex: number): boolean => {
  if (previousIndex < 0) {
    return false;
  } else {
    let previousSender = conversations.value[previousIndex].sender.id;
    let currentSender = conversations.value[index].sender.id; 
    return previousSender === currentSender;
  }
};

// checks whether the message is sent by the authenticated user.
const isSelf = (conversation: IConversation): boolean => {
  // return Boolean(store.user && message.sender.id === store.user.id);
  return Boolean(conversation && conversation.message_round == 'c2s');
};

// checks wether the new message has been sent in a new day or not.
const renderDivider = (index: number, previousIndex: number): boolean => {
  if(previousIndex < 0){
    return false;
  }
  let pre:IConversation = conversations.value[previousIndex];
  let cur:IConversation = conversations.value[index];
  if (isToday(cur.create_time) && isYestoday(pre.create_time)) {
    return true;
  }else{
    return false;
  }
};

// scroll messages to bottom.
onMounted(() => {
  (container.value as HTMLElement).scrollTop = (
    container.value as HTMLElement
  ).scrollHeight;
  preScrollHeight = (container.value as HTMLElement).scrollHeight;
});

onUpdated(()=> {
  const newScrollHeight = (container.value as HTMLElement).scrollHeight;
  if (customerStore.loadMoreFlag) {
    customerStore.loadMoreFlag = false;
    //loadmo要滚动到loadmore之前的位置
    const offset = newScrollHeight - preScrollHeight - 50;
    (container.value as HTMLElement).scrollTop = offset;
    preScrollHeight = newScrollHeight;
  }else{
    (container.value as HTMLElement).scrollTop = newScrollHeight
    preScrollHeight = newScrollHeight;
  }
  
})

const loadData = ()=>{
  console.log('load more load more')
  customerStore.loadMoreFlag = true;
  const keys = Object.keys(customerStore.conversations);
  keys.sort(function(a,b){return parseInt(a) - parseInt(b);});
  const cid = customerStore.customer?.id;
  const wid = customerStore.website?.id;
  if (keys.length > 0 && cid && wid) {
    const minConversationId = keys[0];
    getHistory(cid,wid,parseInt(minConversationId),10).then((res)=>{
      console.log(res);
      const cs  = res.data.conversations
      for(var c  in cs){
        customerStore.addConversation(cs[c]);
      }
    })
  }
  
  
}

</script>

<template>
  <div
    ref="container"
    class="grow px-5 py-5 flex flex-col overflow-y-scroll scrollbar-hidden"
  >
  <InfiniteLoading @infinite="loadData" />
    <div
      v-if="store.status !== 'loading'"
      v-for="(message, index) in conversations"
      :key="index"
    >
      <TimelineDivider v-if="renderDivider(index, index - 1)" />

      <Message
        :message="message"
        :self="isSelf(message)"
        :follow-up="isFollowUp(index, index - 1)"
        :divider="renderDivider(index, index - 1)"      />
    </div>
  </div>
</template>
